const jwt = require('jsonwebtoken');
const JWT_SECRET = 'your-jwt-secret';

module.exports = function(req, res, next) {
    // 从请求头获取token
    const token = req.header('x-auth-token');

    // 检查是否有token
    if (!token) {
        return res.status(401).json({ msg: '没有token，认证失败' });
    }

    try {
        // 验证token
        const decoded = jwt.verify(token, JWT_SECRET);
        req.user = decoded.user;
        next();
    } catch (err) {
        res.status(401).json({ msg: 'token无效' });
    }
}; 